import 'package:account_book/common/constants/storage_key.dart';
import 'package:account_book/common/services/notification_service.dart';
import 'package:account_book/common/services/storage_service.dart';
import 'package:account_book/pages/remind/index.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:get/get.dart';

class RemindController extends GetxController {

  final state = RemindState();

  @override
  void onReady() {
    super.onReady();
    bool remindFlag = StorageService.instance.getBool(StorageKeyConstants.remindFlag);
    state.remindFlag = remindFlag;
    if (remindFlag) {
      String remindTime = StorageService.instance.getString(StorageKeyConstants.remindTime);
      if (remindTime.isNotEmpty) {
        DateTime? dateTime = DateUtil.getDateTime(remindTime);
        if (dateTime!=null) {
          state.remindTime = dateTime;
        }
      }
    }
  }

  void setRemindFlag(bool flag) {
    state.remindFlag = flag;
    _storageSetting();
  }

  void setRemindTime(DateTime dateTime) {
    state.remindTime = dateTime;
    _storageSetting();
  }

  Future<void> _storageSetting() async {
    await NotificationService.instance.cancelAllNotification();
    await StorageService.instance.setBool(StorageKeyConstants.remindFlag, state.remindFlag);
    await StorageService.instance.setString(StorageKeyConstants.remindTime, DateUtil.formatDate(state.remindTime));
    if (state.remindFlag) {
      await NotificationService.instance.scheduleNotification(state.remindTime);
    }
  }
}